package com.like.network;

import android.text.TextUtils;

import com.like.aes.AESUtils;
import com.like.entity.EventWrapper;
import com.like.utils.Constants;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

public class AESInterceptor implements Interceptor {

    public static final String TAG_REFRESH_TOKEN = "refresh_token";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        request = encryptRequest(request);
        Response response = chain.proceed(request);
        response = decryptResponse(response);
        return response;
    }

    private String stringifyRequestBody(Request request) {
        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }

    private Response decryptResponse(Response response) {
        Response decryptedResponse = response;
        try {
            String responseBody = response.body().string();
            JSONObject responseJson = new JSONObject(responseBody);
            if (responseJson.has("Data")) {
                String data = responseJson.getString("Data");
                if (TextUtils.isEmpty(data))
                    return decryptedResponse;
                data = AESUtils.decrypt(data, Constants.AES_KEY, Constants.PROJECT_ID);
                JSONObject jo = new JSONObject(data);
                decodeData(jo);
                responseJson.put("Data", jo);
                ResponseBody decryptedResponseBody = ResponseBody.create(response.body().contentType(), responseJson.toString());
                decryptedResponse = response.newBuilder().body(decryptedResponseBody).build();
            }
            if (responseJson.has("Result")) {
                int result = responseJson.getInt("Result");
                if (result == 4102) {
                    EventBus.getDefault().post(new EventWrapper(null, TAG_REFRESH_TOKEN));
                    String token = Constants.TOKEN;
                    while (Constants.TOKEN.equals(token)) {
                    }
                    responseJson.put("Secret", Constants.TOKEN);
                    ResponseBody body = ResponseBody.create(response.body().contentType(), responseJson.toString());
                    decryptedResponse = response.newBuilder().body(body).build();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return decryptedResponse;
        }
        return decryptedResponse;
    }

    private void decodeData(JSONObject jsonObject) {
        Iterator it = jsonObject.keys();
        while (it.hasNext()) {
            try {
                String key = (String) it.next();
                Object value = jsonObject.get(key);
                if (value instanceof JSONObject) {
                    JSONObject obj = (JSONObject) value;
                } else if (value instanceof JSONArray) {
                    JSONArray array = (JSONArray) value;
                    for (int i = 0; i < array.length(); i++)
                        decodeData(array.getJSONObject(i));
                } else {
                    String data = String.valueOf(value);
                    data = URLDecoder.decode(data, "UTF-8").trim();
                    jsonObject.put(key, data);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private Request encryptRequest(Request request) {
        Request encryptedRequest = request;
        try {
            String requestBody = URLDecoder.decode(stringifyRequestBody(request), "utf-8");
            Map<String, String> params = getQueryMap(requestBody);
            String data = params.get("Data");
            if (data == null)
                return encryptedRequest;
            params.put("Data", AESUtils.encrypt(data, Constants.AES_KEY, Constants.PROJECT_ID));
            String encryptedParams = "";
            for (String key : params.keySet())
                encryptedParams += key + "=" + URLEncoder.encode(params.get(key), "utf-8").trim() + "&";
            encryptedParams.substring(encryptedParams.length() - 2);
            RequestBody encryptedBody = RequestBody.create(request.body().contentType(), encryptedParams);
            encryptedRequest = request.newBuilder().method(request.method(), encryptedBody).build();
        } catch (Exception e) {
            e.printStackTrace();
            return encryptedRequest;
        }
        return encryptedRequest;
    }

    public static Map<String, String> getQueryMap(String query) {
        String[] params = query.split("&");
        Map<String, String> map = new HashMap<>();
        for (String param : params) {
            String name = param.split("=")[0];
            String value = param.split("=")[1];
            map.put(name, value);
        }
        return map;
    }
}
